package com.cyan.note.controller;

import com.cyan.note.common.ApiResult;
import com.cyan.note.dto.admin.ManagerCreateRequest;
import com.cyan.note.dto.admin.ManagerResponse;
import com.cyan.note.dto.admin.ManagerUpdateRequest;
import com.cyan.note.service.AdminManagerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;

/**
 * 超级管理员 - 店长管理控制器
 * 严格按照RBAC权限控制，只有超级管理员可以访问
 * 严格遵循数据隔离原则，只能管理店长账户的系统信息
 * 
 * @author ZhangzhenYu
 * @since 2025-01-14
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/managers")
@RequiredArgsConstructor
@Validated
public class AdminManagerController {

    private final AdminManagerService adminManagerService;

    /**
     * 查询所有店长账户列表（仅系统信息）
     * 权限：仅超级管理员
     */
    @GetMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<List<ManagerResponse>> getAllManagers() {
        try {
            log.info("超级管理员查询所有店长账户列表");
            List<ManagerResponse> managers = adminManagerService.getAllManagers();
            return ApiResult.success("查询店长列表成功", managers);
        } catch (Exception e) {
            log.error("查询店长列表失败", e);
            return ApiResult.error("查询店长列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询店长账户
     * 权限：仅超级管理员
     */
    @GetMapping("/shop/{shopId}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<List<ManagerResponse>> getManagersByShopId(
            @PathVariable @NotNull(message = "店铺ID不能为空") Long shopId) {
        try {
            log.info("超级管理员按店铺查询店长账户, shopId: {}", shopId);
            List<ManagerResponse> managers = adminManagerService.getManagersByShopId(shopId);
            return ApiResult.success("按店铺查询店长成功", managers);
        } catch (IllegalArgumentException e) {
            log.warn("按店铺查询店长参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("按店铺查询店长业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("按店铺查询店长失败", e);
            return ApiResult.error("按店铺查询店长失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态查询店长账户
     * 权限：仅超级管理员
     */
    @GetMapping("/status/{status}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<List<ManagerResponse>> getManagersByStatus(
            @PathVariable @NotBlank(message = "状态不能为空") String status) {
        try {
            log.info("超级管理员按状态查询店长账户, status: {}", status);
            List<ManagerResponse> managers = adminManagerService.getManagersByStatus(status);
            return ApiResult.success("按状态查询店长成功", managers);
        } catch (IllegalArgumentException e) {
            log.warn("按状态查询店长参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("按状态查询店长失败", e);
            return ApiResult.error("按状态查询店长失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询店长账户详情
     * 权限：仅超级管理员
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ManagerResponse> getManagerById(
            @PathVariable @NotNull(message = "用户ID不能为空") Long id) {
        try {
            log.info("超级管理员查询店长账户详情, managerId: {}", id);
            ManagerResponse manager = adminManagerService.getManagerById(id);
            return ApiResult.success("查询店长详情成功", manager);
        } catch (IllegalArgumentException e) {
            log.warn("查询店长详情参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("查询店长详情业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("查询店长详情失败", e);
            return ApiResult.error("查询店长详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建店长账户
     * 权限：仅超级管理员
     */
    @PostMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ManagerResponse> createManager(@Valid @RequestBody ManagerCreateRequest request) {
        try {
            log.info("超级管理员创建店长账户, username: {}, shopId: {}", request.getUsername(), request.getShopId());
            ManagerResponse manager = adminManagerService.createManager(request);
            return ApiResult.success("创建店长账户成功", manager);
        } catch (RuntimeException e) {
            log.warn("创建店长账户业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建店长账户失败", e);
            return ApiResult.error("创建店长账户失败: " + e.getMessage());
        }
    }

    /**
     * 更新店长账户基本信息
     * 权限：仅超级管理员
     */
    @PutMapping
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<ManagerResponse> updateManager(@Valid @RequestBody ManagerUpdateRequest request) {
        try {
            log.info("超级管理员更新店长账户信息, managerId: {}", request.getId());
            ManagerResponse manager = adminManagerService.updateManager(request);
            return ApiResult.success("更新店长信息成功", manager);
        } catch (RuntimeException e) {
            log.warn("更新店长信息业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新店长信息失败", e);
            return ApiResult.error("更新店长信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新店长账户状态
     * 权限：仅超级管理员
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<String> updateManagerStatus(
            @PathVariable @NotNull(message = "用户ID不能为空") Long id,
            @RequestParam @NotBlank(message = "状态不能为空") String status) {
        try {
            log.info("超级管理员更新店长账户状态, managerId: {}, status: {}", id, status);
            boolean success = adminManagerService.updateManagerStatus(id, status);
            if (success) {
                return ApiResult.success("店长账户状态更新成功");
            } else {
                return ApiResult.error("店长账户状态更新失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("更新店长状态参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("更新店长状态业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新店长状态失败", e);
            return ApiResult.error("更新店长状态失败: " + e.getMessage());
        }
    }

    /**
     * 重置店长密码
     * 权限：仅超级管理员
     */
    @PutMapping("/{id}/password")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<String> resetManagerPassword(
            @PathVariable @NotNull(message = "用户ID不能为空") Long id,
            @RequestParam @NotBlank(message = "新密码不能为空") 
            @Size(min = 6, max = 50, message = "密码长度必须在6-50字符之间") String newPassword) {
        try {
            log.info("超级管理员重置店长密码, managerId: {}", id);
            boolean success = adminManagerService.resetManagerPassword(id, newPassword);
            if (success) {
                return ApiResult.success("店长密码重置成功");
            } else {
                return ApiResult.error("店长密码重置失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("重置店长密码参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("重置店长密码业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("重置店长密码失败", e);
            return ApiResult.error("重置店长密码失败: " + e.getMessage());
        }
    }

    /**
     * 删除店长账户
     * 权限：仅超级管理员
     * 警告：这是系统级删除操作，会影响相关数据
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<String> deleteManager(
            @PathVariable @NotNull(message = "用户ID不能为空") Long id) {
        try {
            log.warn("超级管理员删除店长账户, managerId: {}", id);
            boolean success = adminManagerService.deleteManager(id);
            if (success) {
                return ApiResult.success("店长账户删除成功");
            } else {
                return ApiResult.error("店长账户删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("删除店长账户参数错误: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("删除店长账户业务异常: {}", e.getMessage());
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除店长账户失败", e);
            return ApiResult.error("删除店长账户失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户名是否已存在
     * 权限：仅超级管理员
     */
    @GetMapping("/check-username/{username}")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ApiResult<Boolean> checkUsername(
            @PathVariable @NotBlank(message = "用户名不能为空") String username,
            @RequestParam(required = false) Long excludeId) {
        try {
            log.info("超级管理员检查用户名是否存在, username: {}, excludeId: {}", username, excludeId);
            boolean exists;
            if (excludeId != null && excludeId > 0) {
                exists = adminManagerService.isUsernameExists(username, excludeId);
            } else {
                exists = adminManagerService.isUsernameExists(username);
            }
            return ApiResult.success("检查完成", exists);
        } catch (Exception e) {
            log.error("检查用户名失败", e);
            return ApiResult.error("检查用户名失败: " + e.getMessage());
        }
    }
}